<?php
declare (strict_types = 1);

namespace app\front\controller;

use app\BaseController;
use app\exception\HttpExceptions;
use app\libs\Token;
use think\facade\Config;
use think\Request;
use app\model\User as UserModel;
class User extends BaseController
{
   public function login(Request $request) {
       $data = $request-> post();
       if(!isset($data['uname']) || !isset($data['code'])) {
           throw new HttpExceptions('参数不合法');
       }
       $data['avatar'] = isset($data['avatar']) ? $data['avatar'] : 'https://img2.baidu.com/it/u=1661289163,995545644&fm=26&fmt=auto';
       $wx = Config::get('wx');
       $loginUrl = sprintf($wx['login_url'], $wx['app_id'], $wx['app_secret'], $data['code']);
       $result = curl_get($loginUrl);
       $wxResult = json_decode($result, true);
       if (empty($wxResult)) {
           throw new HttpExceptions( '微信服务器内部错误', 503);
       }else{
           if(array_key_exists('errcode',$wxResult))
               throw new HttpExceptions( '传入的code失效');
           $openid = $wxResult['openid'];
           $uid = UserModel::getUser(['openid'=> $openid,'uname' => $data['uname'],'avatar' => $data['avatar']]);
           $authorization = Token::generateToken(compact('uid'));
           return $this->result(compact('authorization'));
       }

   }

}
